﻿using Sidvall.Serialization;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Principal;
using System.Threading.Tasks;

namespace Sidvall.Web.Security
{
	public class EmailValidator : ValidatorBase
	{
		#region Public Members

		public string AuthorityUserInfoEndpoint { get; set; }

		#region IsValidAsync

		public async Task<bool> IsValidAsync(IIdentity identity, NameValueCollection headers, NameValueCollection formValues)
		{
			if (IsIgnored(identity, formValues))
				return true;
			var token = RequestManager.GetAccessToken(headers, formValues);
			if (!string.IsNullOrWhiteSpace(token))
			{
				var userInfo = await Sidvall.SystemContext.Current.AuthenticationManager.GetUserInfoAsync(this.AuthorityUserInfoEndpoint, token);
				if (userInfo.GetEmailVerified())
					return true;
			}
			return false;
		}

		#endregion

		#endregion
		#region Constructors

		public EmailValidator()
		{
		}
		public EmailValidator(string authorityUserInfoEndpoint)
			: this(authorityUserInfoEndpoint, null)
		{
		}
		public EmailValidator(string authorityUserInfoEndpoint, IEnumerable<string> ignoredUsers)
			: base(ignoredUsers)
		{
			this.AuthorityUserInfoEndpoint = authorityUserInfoEndpoint;
		}

		#endregion
	}
}
